//
// Created by TongHua on 2020/12/30.
//

#include <time.h>
#include "Logger.h"

Logger::Logger() {
    m_count = 0;
    m_is_async = false;
}

Logger::~Logger() {
    if ( m_fp != NULL )
    {
        fclose( m_fp );
    }
}

bool Logger::Init(const char *_filename, int _log_buf_size, int _split_lines, int _max_queue_size) {
    if ( _max_queue_size >= 1 )
    {
        m_is_async = true;
        m_log_queue = new BlockQueue< string >(_max_queue_size);
        pthread_t pid;
        pthread_create( &pid, NULL, FlushLogThread, NULL );
    }
    m_log_buf_size = _log_buf_size;
    m_buf = new char [m_log_buf_size];
    memset( m_buf, '\0', m_log_buf_size );
    m_split_lines = _split_lines;

    time_t t = time( NULL );
    tm* sys_tm = localtime( &t );
    tm my_tm = *sys_tm;

    const char *p = strrchr(_filename, '/');
    char log_full_name[256] = {0};

    if (p == NULL)
    {
        snprintf(log_full_name, 255, "%d_%02d_%02d_%s", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, _filename);
    }
    else
    {
        strcpy(m_log_name, p + 1);
        strncpy(m_dir_name, _filename, p - _filename + 1);
        snprintf(log_full_name, 255, "%s%d_%02d_%02d_%s", m_dir_name, my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday, m_log_name);
    }

    m_today = my_tm.tm_mday;

    m_fp = fopen(log_full_name, "a");
    printf("open %s\n",log_full_name);
    if (m_fp == NULL)
    {
        return false;
    }

    return true;
}

void Logger::WriteLog(int _level, const char *format, ...)
{
    struct timeval now = {0, 0};
    gettimeofday(&now, NULL);
    time_t t = now.tv_sec;
    struct tm *sys_tm = localtime(&t);
    struct tm my_tm = *sys_tm;
    char s[16] = {0};
    switch (_level)
    {
        case 0:
            strcpy(s, "[debug]:");
            break;
        case 1:
            strcpy(s, "[info]:");
            break;
        case 2:
            strcpy(s, "[warn]:");
            break;
        case 3:
            strcpy(s, "[erro]:");
            break;
        default:
            strcpy(s, "[info]:");
            break;
    }
    //写入一个log，对m_count++, m_split_lines最大行数
    m_mutex.Lock();
    m_count++;

    if (m_today != my_tm.tm_mday || m_count % m_split_lines == 0) //everyday log
    {

        char new_log[256] = {0};
        fflush(m_fp);
        fclose(m_fp);
        char tail[16] = {0};

        snprintf(tail, 16, "%d_%02d_%02d_", my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday);

        if (m_today != my_tm.tm_mday)
        {
            snprintf(new_log, 255, "%s%s%s", m_dir_name, tail, m_log_name);
            m_today = my_tm.tm_mday;
            m_count = 0;
        }
        else
        {
            snprintf(new_log, 255, "%s%s%s.%lld", m_dir_name, tail, m_log_name, m_count / m_split_lines);
        }
        m_fp = fopen(new_log, "a");
    }

    m_mutex.UnLock();

    va_list valst;
    va_start(valst, format);

    string log_str;
    m_mutex.Lock();

    //写入的具体时间内容格式
    int n = snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06ld %s ",
                     my_tm.tm_year + 1900, my_tm.tm_mon + 1, my_tm.tm_mday,
                     my_tm.tm_hour, my_tm.tm_min, my_tm.tm_sec, now.tv_usec, s);

    int m = vsnprintf(m_buf + n, m_log_buf_size - 1, format, valst);
    m_buf[n + m] = '\n';
    m_buf[n + m + 1] = '\0';
    log_str = m_buf;

    m_mutex.UnLock();

    if (m_is_async && !m_log_queue->IsFull())
    {
        m_log_queue->Push(log_str);
    }
    else
    {
        m_mutex.Lock();
        fputs(log_str.c_str(), m_fp);
        m_mutex.UnLock();
    }

    va_end(valst);
}

void Logger::Flush(void)
{
    m_mutex.Lock();
    //强制刷新写入流缓冲区
    fflush(m_fp);
    m_mutex.UnLock();
}
